package pt.mleiria.crypto.signatures;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

public class VerifySignatureMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 3) {
			System.out.println("Usage: VerifySignatureMain "
					+ "publickeyfile signaturefile " + "datafile");
		} else {
			try {
				//Carregar a chave pública
				//final FileInputStream keyfis = new FileInputStream(args[0]);
				final FileInputStream keyfis = new FileInputStream("D:\\workspace\\Private_WS\\cryptoApp\\Crypto\\mypk");
				final byte[] encKey = new byte[keyfis.available()];
				keyfis.read(encKey);
				keyfis.close();
				//Gerar a chave pública
				final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
				final KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
				final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
				//Carregar o ficheiro de assinatura
				//final FileInputStream sigfis = new FileInputStream(args[1]);
				final FileInputStream sigfis = new FileInputStream("D:\\workspace\\Private_WS\\cryptoApp\\Crypto\\sig");
				final byte[] sigToVerify = new byte[sigfis.available()]; 
				sigfis.read(sigToVerify);
				sigfis.close();
				//Instanciar o objecto Signature
				final Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
				//Inicializar o objecto com a chave publica
				sig.initVerify(pubKey);
				//Carregar os dados para serem verificados
				//final FileInputStream datafis = new FileInputStream(args[2]);
				final FileInputStream datafis = new FileInputStream("D:\\workspace\\Private_WS\\cryptoApp\\Crypto\\src\\main\\java\\pt\\mleiria\\crypto\\signatures\\manuelLeiria");
				final BufferedInputStream bufin = new BufferedInputStream(datafis);

				final byte[] buffer = new byte[1024];
				int len;
				while (bufin.available() != 0) {
				    len = bufin.read(buffer);
				    sig.update(buffer, 0, len);
				};

				bufin.close();
				//Verificar a assinatura
				boolean verifies = sig.verify(sigToVerify);
				System.out.println("signature verifies: " + verifies);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

}
